<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: snzo.chen
 * @Date: 2023-11-16 15:01:18
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-12-14 14:49:15
-->
<template>
  <ActionTable @addRow="showModal('ADD', { isOpen: 0 })" />
  <a-table :columns="columns" :row-key="(record) => record.id" :data-source="state.packageDayOfData"
    :pagination="state.pagination" :loading="state.loading" @change="handleTableChange">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'ticketMenu'">
        <span>{{ menuIdToName(ticketMenu) }}</span>
      </template>
      <template v-if="column.key === 'ticketPackageId'">
        <span>{{ packageIdToName(ticketPackageId) }}</span>
      </template>
      <template v-if="column.key === 'ticketDate'">
        <span>{{ formatToDate(record.ticketDate) }}</span>
      </template>
      <template v-if="column.key === 'status'">
        <a-tag>{{ PackageDayStatus[record.status] }}</a-tag>
      </template>
      <template v-if="column.key === 'action'">
        <TableRowAction :showSelect="false" @updateItem="showModal('UPDATE', record)" @deleteItem="delRow(record.id)" />
      </template>
    </template>
  </a-table>
  <contextHolder />
</template>
<script lang="ts" setup>
import { selectAllPackage } from "@/api/ticket/package";
import { TableProps, message as $message, Modal } from "ant-design-vue";
import { h, onMounted, reactive, ref, watch } from "vue";
import dayjs from "dayjs";
import 'dayjs/locale/zh-cn';
import { useRoute } from "vue-router";
import { paginationToQuery } from "@/utils/common";
import {
  deleteTicketPackageDay,
  insertTicketPackageDay,
  selectPackageDayByExample,
  updateTicketPackageDay,
} from "@/api/ticket/packageDay";
import { formatToDate } from "@/utils/dateUtil";
import { selectAllMenu } from "@/api/ticket/menu";
import PackageDaySchemas from "./packageDaySchemas.vue";
import { modalTitleEnum } from "@/enums/modalEnum";
import { PackageDayStatus } from "./stateEnum";
const route = useRoute();
const [modal, contextHolder] = Modal.useModal();
const childRef = ref();

const sharedOnCell = (_, index) => {
  if (index === 0) {
    return { rowSpan: 10 };
  }
  if (index > 0) {
    return { rowSpan: 0 };
  }
};

const columns = [
  {
    dataIndex: "ticketMenu",
    title: "类别名称",
    key: "ticketMenu",
    align: "center",
    customCell: sharedOnCell,
  },
  {
    dataIndex: "ticketPackageId",
    title: "商品名称",
    key: "ticketPackageId",
    align: "center",
    customCell: sharedOnCell,
  },
  {
    dataIndex: "id",
    title: "ID",
    key: "id",
    align: "center",
  },
  {
    dataIndex: "ticketDate",
    title: "使用日期",
    key: "ticketDate",
    align: "center",
  },
  {
    dataIndex: "num",
    title: "库存数量",
    key: "num",
    align: "center",
  },
  {
    dataIndex: "status",
    title: "状态",
    key: "status",
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    align: "center",
  },
];
const ticketPackageId = ref(0);
const ticketMenu = ref(0);
let menuOfData: any[] = [];
let packageOfData: any[] = [];
const state = reactive({
  loading: true,
  packageDayOfData: <API.TicketPackageDay>[],
  pagination: {
    pageSize: 10,
    current: 1,
    total: 0,
    showTotal: (total) => `总${total}条`,
  },
});

watch(
  () => route.query.type,
  (newVal, oldVal) => {
    if (newVal === oldVal) return;
    loadData();
  }
);

/**
 * 获取数据
 */
const loadData = async () => {
  const { seachList, seachTotal } = await selectPackageDayByExample(
    { ticketPackageId: ticketPackageId.value },
    paginationToQuery(state.pagination)
  );
  state.packageDayOfData = seachList;
  state.pagination.total = seachTotal;
  const menuResult = await selectAllMenu({ pageNum: 1, pageSize: 999 });
  const packageResult = await selectAllPackage({ pageNum: 1, pageSize: 999 });
  menuOfData = menuResult.seachList;
  packageOfData = packageResult.seachList;
  state.loading = false;
};

const menuIdToName = (menuId: number): string => {
  let menuName = "";
  for (const menuItem of menuOfData) {
    if (menuItem.id === menuId) {
      menuName = menuItem.menuName;
      break;
    }
  }
  return menuName;
};

const packageIdToName = (ticketPackageId): string => {
  let packageName = "";
  for (const packageItem of packageOfData) {
    if (packageItem.id === ticketPackageId) {
      packageName = packageItem.packageName;
      break;
    }
  }
  return packageName;
};

/**
 * 分页切换
 * @param page
 */
const handleTableChange: TableProps["onChange"] = (page) => {
  state.pagination.current = page.current!;
  loadData();
};

/**
 *
 * @param type
 * @param data
 */
const showModal = (type: string, data?: any) => {
  data.ticketDate
    ? (data.ticketDate = dayjs(data.ticketDate, "YYYY-MM-DD"))
    : (data.ticketDate = null);
  const packageDayForm = () => h(PackageDaySchemas, { ref: childRef, formData: data });
  modal.confirm({
    title: modalTitleEnum[type] + "库存",
    icon: null,
    content: packageDayForm,
    okText: "提交",
    cancelText: "取消",
    async onOk() {
      const { id, num, status, ticketDate } = childRef.value.formState;
      console.log('🚀 ~ onOk ~ ticketDate:', dayjs(ticketDate,'YYYY-MM-DD'))
      console.log('🚀 ~ onOk ~ ticketDate:', ticketDate)
      
      if (type === "ADD") {
        const { msg } = await insertTicketPackageDay({
          num,
          status,
          ticketDate: dayjs(ticketDate, "YYYY-MM-DD").toString(),
          ticketMenu: ticketMenu.value,
          ticketPackageId: ticketPackageId.value,
        });
        msg === "success" ? loadData() : $message.error(msg);
      } else if (type === "UPDATE") {
        const { msg } = await updateTicketPackageDay({
          id,
          num,
          status,
          ticketDate: dayjs(ticketDate, "YYYY-MM-DD").toString(),
          ticketMenu: ticketMenu.value,
          ticketPackageId: ticketPackageId.value,
        });
        msg === "success" ? loadData() : $message.error(msg);
      }
    },
    onCancel() {
      Modal.destroyAll();
    },
  });
};

/**
 * 删除商品
 */
const delRow = async (id) => {
  const { msg } = await deleteTicketPackageDay({ id });
  msg === "success" ? $message.success("删除成功") : $message.error(msg);
  loadData();
};

onMounted(() => {
  ticketMenu.value = Number(route.params.ticketMenu);
  ticketPackageId.value = Number(route.params.ticketPackageId);
  loadData();
});
</script>
<style lang="less" scoped>
.action-row {
  button {
    margin-left: 10px;

    &:first-child {
      margin-left: 0;
    }
  }
}
</style>
